package com.cll.learn.filter;

import org.apache.dubbo.rpc.RpcContext;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 描述信息:
 * 根据request对象，将请求ip设置到rpcContext中
 * @author CLL
 * @version 1.0
 * @date 2020/10/9 16:46
 */
public class DubboTraffic {

    private static final String REQUEST_IP = "request_ip";

    /**
     * 从rpcContext中获取IP
     * @return
     */
    public static String getRequestIp(){
        System.out.println("从rpcContext中获取IP");
        return RpcContext.getContext().getAttachment(REQUEST_IP);
    }

    /**
     * 将IP信息保存到rpcContext中
     * @param request   请求信息
     */
    public static void saveFrom(ServletRequest request) {
        System.out.println("放置请求IP到rpcContext中");
        if (null == request) {
            return;
        }
        if (request instanceof HttpServletRequest) {
            RpcContext.getContext().setAttachment(REQUEST_IP, RequestIpUtil.getIPAddress((HttpServletRequest)request));
        } else {
            RpcContext.getContext().setAttachment(REQUEST_IP, request.getRemoteAddr());
        }
    }
}